/**
 * @description useFetch方法封装
 */
import signConfig from '@/configs/sign'
import { cso } from '@/utils/sign'
import localeConfig from '@/configs/locale'

export function useFetchData(
  url,
  { method = 'get', query = {}, params = {}, body = {}, headers = {}, baseURL = '' } = {}
) {
  return new Promise((resolve, reject) => {
    // 获取本地语言
    const { locale } = useI18nHook()

    useFetch(url, {
      method,
      query,
      params,
      body,
      headers,
      baseURL,
      onRequest({ options }) {
        if (options.method?.toLocaleUpperCase() === 'GET') {
          const query = {
            ...options.query,
            // TODO国际化语言先默认使用中文
            // 'cb-lang': localeConfig[locale.value]
            'cb-lang': 'zh-CN'
          }
          options.query = cso(query, signConfig.ak)
        } else {
          const body = {
            ...options.body,
            // TODO国际化语言先默认使用中文
            // 'cb-lang': localeConfig[locale.value]
            'cb-lang': 'zh-CN'
          }
          options.body = cso(body, signConfig.ak)
        }
      },
      onRequestError({ error }) {
        return Promise.reject(error)
      },
      onResponse({ response }) {
        return response
      },
      onResponseError({ response }) {
        return Promise.reject(response)
      }
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
